package com.myapp.web.action.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.myapp.util.Constants;
import com.myapp.util.xwork.PropertiesAware;
import com.opensymphony.xwork2.Action;

public class DownloadAction implements Action,PropertiesAware,ServletRequestAware{

	private Properties props;
	private HttpServletRequest request;
	
	private String getFileName(){	
		String fileName = null;
		System.out.println(request.getRequestURL().toString());
		System.out.println(request.getQueryString());
		String contextPath = request.getRequestURL().toString();// ServletActionContext.getServletContext().getContextPath();
		String name = contextPath.substring(contextPath.lastIndexOf('?') + 1);
		if(props != null){
			fileName = props.getProperty(Constants.APP_DOWNLOAD_DIR) + File.separator + request.getQueryString();
		}else
		{
			fileName = ServletActionContext.getServletContext().getRealPath(contextPath);
		}
		return fileName;
	}
	
	public InputStream getTargetFile() throws Exception{
		FileInputStream fis = new FileInputStream(getFileName());
		return fis;
	}
	
	@Override
	public String execute() throws Exception {
		return SUCCESS;
	}

	@Override
	public void setProperties(Properties props) {
		this.props = props;
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request ;		
	}
}
